package com.taikang.auth.interceptor;

import com.taikang.auth.entity.User;
import com.taikang.base.constant.SessionConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import static com.taikang.base.AdminUserHolder.remove;
import static com.taikang.base.AdminUserHolder.setCurrentUser;

/**
 * 后台用户登录拦截器
 *
 * @version 1.0
 * @creator taikang
 * @create-time Jun 19, 2015   2:09:07 PM
 */
public class AdminLoginInterceptor extends HandlerInterceptorAdapter {

    @Value("${dev.mode}")
    private String devMode;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断用户是否登录
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(SessionConstant.CURRENT_USER);
        if (null == user) {
            //判断请求方式
            String requestType = request.getHeader("X-Requested-With");
            if (StringUtils.isNotBlank(requestType) && StringUtils.equals("XMLHttpRequest", requestType)) {
                //异步请求
                response.setContentType("text/json;charset=UTF-8");
                response.getWriter().write("{\"status\":\"error\",\"message\":\"登录超时，请重新登录\"}");
                return false;
            }
            response.sendRedirect(request.getContextPath() + "/admin/login.htm");
            return false;
        }
        setCurrentUser(user);
        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        remove();
        super.afterCompletion(request, response, handler, ex);
    }
}
